﻿//PlazaFormatter.cs
//Copyright (c) 2013 StockSharp LLC, all rights reserved.
//This code module is part of StockSharp library.
//This code is licensed under the GNU GENERAL PUBLIC LICENSE Version 3.
//See the file License.txt for the license details.
//More info on: http://stocksharp.com

namespace StockSharp.Plaza
{
	using System;
	using System.Globalization;

	using StockSharp.BusinessEntities;

	/// <summary>
	/// Специальный класс для форматирования .NET данных в формат Plaza, и наоборот.
	/// </summary>
	static class PlazaFormatter
	{
		/// <summary>
		/// Конвертирует значение типа decimal 
		/// </summary>
		/// <param name="value"></param>
		/// <returns></returns>
		public static string ToPlazaString(this decimal value)
		{
			return value.ToString("F5", CultureInfo.InvariantCulture).PadLeft(16, '0');
		}

		/// <summary>
		/// Конвертирует значение типа DateTime в формат Plaza
		/// </summary>
		/// <param name="value"></param>
		/// <returns></returns>
		public static string ToPlazaString(this DateTime value)
		{
			return value.ToString("yyyyddMM");
		}

		/// <summary>
		/// Конвертирует представление даты в формате Plaza в тип DateTime.
		/// </summary>
		/// <param name="n"></param>
		/// <returns></returns>
		public static DateTime ToDateTime(this ulong n)
		{
			var milli = (int)(n % 1000);
			n /= 1000;
			var sec = (int)(n % 100);
			n /= 100;
			var min = (int)(n % 100);
			n /= 100;
			var hour = (int)(n % 100);
			n /= 100;
			var day = (int)(n % 100);
			n /= 100;
			var month = (int)(n % 100);
			n /= 100;

			return new DateTime((int)n, month, day, hour, min, sec, milli);
			//return DateTime.ParseExact(str, "yyyyMMddHHmmssfff", null);
		}

		public static string ToClientCode(this Portfolio portfolio)
		{
			if (portfolio == null)
				throw new ArgumentNullException("portfolio");

			return portfolio.Name.Substring(portfolio.Name.Length - 3);
		}

		public static MicexSecurityState ToMicexSecurityState(this string micexState)
		{
			if (micexState == null)
				throw new ArgumentNullException("micexState");

			switch (micexState)
			{
				case "A":
					return MicexSecurityState.Active;
				case "S":
					return MicexSecurityState.Stopped;
				case "N":
					return MicexSecurityState.Blocked;
				default:
					throw new ArgumentOutOfRangeException("micexState");
			}
		}

		public static OrderDirections ToOrderDirections(this string direction)
		{
			return direction == "B" ? OrderDirections.Buy : OrderDirections.Sell;
		}
	}
}